<template>
  <div class="app-main-content">
    <div class="tree-wrap el-col el-col-6 h100">
      <scmsa-tree
        ref="tree"
        class="tree orgtreee"
        :data="categoryOfPublicCodeData"
        :props="defaultProps"
        :load="loadNode"
        node-key="id"
        :title="id"
        :expend-on-click-node="false"
        :filter-node-method="filterTreeNode"
        :highlight-current="true"
        :action-menus="treeActionMenus"
        :show-add-btn="false"
        :custom-icon="false"
        lazy
        @on-context-item="handleContextItem"
        @before-node-contextmenu="beforeNodeMenus"
        @node-click="handleNodeClick" />
    </div>
    <div class="table-wrap el-col el-col-18">
      <el-drawer
        :wrapper-closable="false"
        :title="formTitle"
        :visible.sync="showCreateWin"
        size="450px"
        :with-header="false">
        <div class="drawer__content">
          <div>
            <el-form
              ref="createForm"
              :model="form"
              label-width="120px">
              <el-form-item
                label="父类别 :">
                <el-input
                  v-model="form.parentLabel"
                  :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="类别值 :">
                <el-input
                  v-model="form.value"
                  :disabled="isEdit"></el-input>
              </el-form-item>
              <el-form-item label="类别名称 :">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="序号 :">
                <el-input v-model="form.sequence"></el-input>
              </el-form-item>
              <el-form-item label="备注 :">
                <el-input
                  v-model="form.memo"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                  @input="ChangeInput($event)">
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="drawer__footer">
            <el-button @click="cancelCreateWin">
              取 消
            </el-button>
            <el-button
              v-oauth
              type="primary"
              data-oauthUuid="1604911601646"
              :loading="loading"
              @click="creatChildNode">
              {{ loading ? '提交中 ...' : '确 定' }}
            </el-button>
          </div>
        </div>
      </el-drawer>
      <el-drawer
        :wrapper-closable="false"
        :title="codeFormTitle"
        :visible.sync="showCodeCreateWin"
        size="450px"
        :with-header="false">
        <div class="drawer__content">
          <div>
            <el-form
              ref="codeCreateForm"
              :model="codeForm"
              label-width="120px">
              <el-form-item
                label="父类别 :">
                <el-input
                  v-model="codeForm.parentLabel"
                  :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="编码值 :">
                <el-input
                  v-model="codeForm.value"
                  :disabled="isEdit"></el-input>
              </el-form-item>
              <el-form-item label="编码名称 :">
                <el-input v-model="codeForm.name"></el-input>
              </el-form-item>
              <el-form-item label="序号 :">
                <el-input v-model="codeForm.sequence"></el-input>
              </el-form-item>
              <el-form-item label="备注 :">
                <el-input
                  v-model="codeForm.memo"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                  @input="ChangeInput($event)">
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="drawer__footer">
            <el-button @click="cancelCodeCreateWin">
              取 消
            </el-button>
            <el-button
              v-oauth
              type="primary"
              :loading="loading"
              data-oauthUuid="1604911638514"
              @click="creatCodeChildNode">
              {{ loading ? '提交中 ...' : '确 定' }}
            </el-button>
          </div>
        </div>
      </el-drawer>
      <div>
        <el-tabs
          v-model="activeName"
          type="card">
          <el-tab-pane
            label="子类别"
            name="1">
            <div style="padding:16px;">
              <div>
                <el-row>
                  <el-button
                    type="danger"
                    v-oauth
                    icon="el-icon-delete"
                    data-oauthUuid="1604909298436"
                    :disabled="!selectedTableNode.length"
                    @click="mulDelete">
                    删除
                  </el-button>
                  <el-button
                    icon="el-icon-refresh"
                    type="success"
                    @click="refresh">
                    刷新
                  </el-button>
                </el-row>
              </div>
              <div class="margin-top-12">
                <scmsa-table
                  ref="table"
                  :column="catacolumn"
                  :data="selectedNodeData"
                  :total="selectedNodeData.length"
                  :height="tableHeight"
                  border
                  align="left"
                  :row-key="getRowKeys"
                  @selection-change="selectionRowsChange">
                </scmsa-table>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="编码值"
            name="2">
            <div style="padding:16px;">
              <div>
                <el-row>
                  <el-button
                    v-show="curFocusNode && curFocusNode.zfFlag !== '1'"
                    v-oauth
                    icon="el-icon-plus"
                    type="primary"
                    data-oauthUuid="1604909212681"
                    @click="createCodeNode">
                    增加
                  </el-button>
                  <el-button
                    v-oauth
                    type="danger"
                    icon="el-icon-delete"
                    data-oauthUuid="1604909298432"
                    :disabled="!selectedCodeTableNode.length"
                    @click="mulCodeDelete">
                    删除
                  </el-button>
                  <el-button
                    icon="el-icon-refresh"
                    type="success"
                    @click="refresh">
                    刷新
                  </el-button>
                </el-row>
              </div>
              <div class="margin-top-12">
                <scmsa-table
                  ref="table"
                  :column="codeColumn"
                  :data="selectedCodeData"
                  :total="selectedCodeData.length"
                  :height="tableHeight"
                  border
                  align="left"
                  :row-key="getRowKeys"
                  @selection-change="selectionCodeRowsChange">
                </scmsa-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import request from '@/utils/request'
  // import i18n from '../../../lang/index'
  import syscodeService from '@/api/syscodeService'
  import colume from './colume'

  export default {
    name: 'SysCode',
    mixins: [colume],
    data() {
      return {
        isEdit: true,
        selectedTypeCode: '',
        codeFormTitle: '',
        showCodeCreateWin: false,
        originData: '',
        activeName: '1',
        activeNames: ['1', '2'],
        loading: false,
        base: {
          baseUrl: process.env.VUE_APP_OAUTH_ADMIN_API,
          axiosRequest: request
        },
        categoryOfPublicCodeData: [
          {
            id: '1',
            label: '系统编码',
            sequence: 1,
            isEdit: false, // 是否为修改态
            children: [
              {
                id: '1-1',
                sequence: 1,
                label: '公共值集',
                code: 'abc',
                isEdit: false,
                children: [{
                  id: '1-1-1',
                  sequence: 1,
                  label: '是否',
                  isEdit: false,
                  code: 'if'
                }]
              }, {
                id: '1-2',
                sequence: 2,
                label: '发布管理',
                code: 'pub',
                isEdit: false,
                children: [{
                  id: '1-2-1',
                  sequence: 1,
                  label: '程序发布类型',
                  isEdit: false,
                  code: 'type'
                }]
              }
            ]
          }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        selectedNodeData: [],
        selectedCodeData: [],
        showEmpty: true,
        showCreateWin: false,
        // localI18n: i18n.messages[i18n.locale],
        formTitle: '',
        codeForm: {
          id: '',
          parentLabel: '',
          value: '',
          name: '',
          sequence: '',
          parentId: ''
        },
        form: {
          id: '',
          parentLabel: '',
          value: '',
          name: '',
          sequence: '',
          parentId: ''
        },
        searchNode: {
          keyWord: ''
        },
        selectedTableNode: [],
        selectedCodeTableNode: [],
        curModifyNode: '',
        curClickNode: '',
        reslove: ''
      }
    },
    computed: {
      tableHeight() {
        return this.$store.state.settings.tableHeight
      },
      routeName() {
        return this.$route.name
      },
      treeActionMenus() {
        return [
          {
            id: 'add',
            label: '添加',
            icon: 'el-icon-plus',
            disabled: this.curClickNode.zfFlag === '1'
          }, {
            id: 'edit',
            label: '编辑',
            icon: 'el-icon-edit',
            disabled: this.curClickNode.zfFlag === '1'
          }, {
            id: 'del',
            label: '删除',
            icon: 'el-icon-delete',
            disabled: this.curClickNode.parentId === null
          }, {
            id: 'refresh',
            label: '刷新',
            icon: 'el-icon-refresh'
          }
        ]
      }
    },
    mounted() {

    },
    methods: {
      getRowKeys(row) {
        return row.id
      },
      cancelCodeCreateWin() {
        this.showCodeCreateWin = false
      },
      // tree右键触发菜单显示事件
      beforeNodeMenus({ e, data, node, cb }) {
        this.curClickNode = data
        cb()
      },
      // 右键菜单点击事件
      handleContextItem({ node, data, contextmenuItem }) {
        switch (contextmenuItem.id) {
        case 'add':
          this.form.parentLabel = data.label
          this.form.parentId = data.id
          this.createNode()
          break
        case 'edit':
          this.handleEdit(data)
          break
        case 'del':
          // 删除前需先删除其子类，避免数据残余
          syscodeService.getList({ parentid: data.id, name: '' }).then(dd => {
            if (dd.data.length !== 0) {
              this.$alert('执行该操作前请先删除其下所有子类别及编码值。', '提示', {
                confirmButtonText: '确定'
              })
            } else {
              this.$confirm('请确认是否删除该系统编码？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                const parentId = data.parentId
                syscodeService.delete({ ids: data.id }).then(data => {
                  this.$message({
                    type: 'success',
                    message: '删除成功！'
                  })
                  this.refreshNodeBy(parentId)
                  this.refresh()
                })
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除。'
                })
              })
            }
          })
          break
        // 刷新
        default:
          this.refreshTreeNode(node, data)
          break
        }
      },
      refreshTreeNode(node, data) {
        this.$set(node, 'loading', true)
        syscodeService.getList({ parentid: data.id, name: '' }).then(data => {
          const temp = []
          data.data.forEach(item => {
            item.label = item.name
            if (item.type === 'cata') {
              temp.push(item)
            }
          })
          this.$refs['tree'].$refs['goTree'].updateKeyChildren(node.key, temp)
          this.$set(node, 'loading', false)
          if (data.data.length) {
            this.$set(node, 'expanded', true)
            this.$set(node, 'isLeaf', false)
          } else {
            this.$set(node, 'isLeaf', true)
          }
        })
      },

      // 搜索过滤
      filterTreeNode(value, data) {
        if (data.name.indexOf(value) > -1) {
          return data
        }
      },
      // 加载子节点数据
      loadNode(node, resolve) {
        let parentid = ''
        this.reslove = resolve
        if (node.level !== 0) {
          parentid = node.data.id
        }
        syscodeService.getList({ parentid: parentid, name: '' }).then(data => {
          const cateList = []
          if (data && data.data && data.data.length !== 0) {
            data.data.forEach(element => {
              element.label = element.name
              if (element.type === 'cata') {
                cateList.push(element)
              }
            })
          }
          return resolve(cateList)
        })
      },
      // 选中节点数据
      handleNodeClick(e) {
        // 默认添加子节点
        // 查询子集
        this.curFocusNode = e
        this.refresh()
        if (!e.children) {
          this.$set(e, 'children', [])
        }
        this.form.parentLabel = e.name
        this.codeForm.parentLabel = e.name
        this.form.parentId = e.id
        this.showEmpty = false
      },
      // 修改系统编码类别
      handleEdit(e) {
        if (e.row) {
          this.curModifyNode = e.row
        } else {
          this.curModifyNode = e
        }
        this.isEdit = true
        if (this.curModifyNode.type === 'code') {
          this.codeFormTitle = '修改公共编码信息'
          this.codeForm.parentId = this.curModifyNode.parentId
          this.codeForm.id = this.curModifyNode.id
          this.codeForm.memo = this.curModifyNode.memo
          this.codeForm.value = this.curModifyNode.value
          this.codeForm.name = this.curModifyNode.name
          this.codeForm.sequence = this.curModifyNode.sequence
          this.showCodeCreateWin = true
        } else {
          this.formTitle = '修改公共编码类别信息'
          this.form.parentId = this.curModifyNode.parentId
          this.form.id = this.curModifyNode.id
          this.form.memo = this.curModifyNode.memo
          this.form.value = this.curModifyNode.value
          this.form.name = this.curModifyNode.name
          this.form.sequence = this.curModifyNode.sequence
          this.showCreateWin = true
        }
      },
      // 删除单个
      handleDelete(e) {
        const msg = e.type === 'code' ? '请确认是否删除该公共编码?' : '请确认是否删除该系统编码类别?'
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          syscodeService.delete({ ids: e.row.id }).then(data => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.refresh()
            this.refreshNodeBy(e.parentId)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      selectionRowsChange(e) {
        this.selectedTableNode = e
      },
      selectionCodeRowsChange(e) {
        this.selectedCodeTableNode = e
      },
      // 创建或修改系统编码类别
      creatChildNode() {
        if (this.formTitle !== '修改公共编码类别信息') { // 创建
          const createParam = {
            sequence: this.form.sequence,
            name: this.form.name,
            value: this.form.value,
            parentId: this.form.parentId,
            memo: this.form.memo,
            type: 'cata'
          }
          syscodeService.create(createParam).then(data => {
            this.refresh()
            this.refreshNodeBy(this.form.parentId)
            this.cancelCreateWin()
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
          })
        } else { // 修改
          const modifyParam = {
            id: this.form.id,
            sequence: this.form.sequence,
            name: this.form.name,
            value: this.form.value,
            parentId: this.form.parentId,
            memo: this.form.memo,
            type: 'cata'
          }
          syscodeService.update(modifyParam).then(data => {
            this.refresh()
            this.refreshNodeBy(this.form.parentId)
            this.cancelCreateWin()
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
          })
        }
        this.initForm()
        this.showCreateWin = false
      },
      // 创建或修改公共编码
      creatCodeChildNode() {
        if (this.codeFormTitle.indexOf('增加') > -1) {
          const createParam = {
            sequence: this.codeForm.sequence,
            name: this.codeForm.name,
            value: this.codeForm.value,
            parentId: this.codeForm.parentId,
            memo: this.codeForm.memo,
            type: 'code'
          }
          syscodeService.create(createParam).then(data => {
            this.refreshNodeBy(this.codeForm.parentId)
            this.refresh()
            this.cancelCodeCreateWin()
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
          })
        } else { // 修改
          const modifyParam = {
            id: this.codeForm.id,
            sequence: this.codeForm.sequence,
            name: this.codeForm.name,
            value: this.codeForm.value,
            parentId: this.codeForm.parentId,
            memo: this.codeForm.memo,
            type: 'code'
          }
          syscodeService.update(modifyParam).then(data => {
            this.refreshNodeBy(this.codeForm.parentId)
            this.refresh()
            this.cancelCodeCreateWin()
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
          })
        }
      },
      refreshNodeBy(id) {
        const node = this.$refs.tree.$refs.goTree.getNode(id) // 通过节点id找到对应树节点对象
        node.loaded = false
        node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
      },
      // 刷新编码类别
      refresh() {
        if (!(this.curFocusNode && this.curFocusNode.id)) {
          return
        }
        syscodeService.getList({ parentid: this.curFocusNode.id, name: '' }).then(data => {
          const cateList = []
          const codeList = []
          data.data.forEach(element => {
            if (element.type === 'cata') {
              cateList.push(element)
            } else {
              codeList.push(element)
            }
          })

          this.selectedNodeData = cateList
          this.selectedCodeData = codeList
        })
      },
      initForm() {
        this.form.sequence = ''
        this.form.name = ''
        this.form.code = ''
        this.form.id = ''
      },
      // 关闭创建界面
      cancelCreateWin() {
        this.showCreateWin = false
      },
      // 打开创建界面
      createNode() {
        if (!this.form.parentId) {
          this.$alert('请先选择一个公共编码类别。', '提示', {
            confirmButtonText: '确定'
          })
          return
        }
        this.isEdit = false
        this.form.value = ''
        this.form.sequence = ''
        this.form.name = ''
        this.form.memo = ''
        this.formTitle = '增加子类别'
        this.showCreateWin = true
      },
      createCodeNode() {
        this.isEdit = false
        this.codeForm.parentLabel = this.curFocusNode.name
        this.codeForm.parentId = this.curFocusNode.id
        this.codeForm.type = 'code'
        this.codeForm.name = ''
        this.codeForm.value = ''
        this.codeForm.sequence = ''
        this.codeForm.memo = ''
        this.codeFormTitle = '增加编码值'
        this.showCodeCreateWin = true
      },
      // 批量删除节点
      mulDelete() {
        const ids = []
        let parentId = ''
        this.selectedTableNode.forEach(item => {
          ids.push(item.id)
          parentId = item.parentId
        })
        this.$confirm('请确认是否删除已选系统编码类别?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          syscodeService.delete({ ids: ids.toString() }).then(data => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.refresh()
            this.refreshNodeBy(parentId)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      ChangeInput(e) {
        this.$forceUpdate()
      },
      // 批量删除公共编码
      mulCodeDelete() {
        const ids = []
        let parentId = ''
        this.selectedCodeTableNode.forEach(item => {
          ids.push(item.id)
          parentId = item.parentId
        })
        this.$confirm('请确认是否删除已选公共编码?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          syscodeService.delete({ ids: ids.toString() }).then(data => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.refresh()
            this.refreshNodeBy(parentId)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 作废
      handleCancel(e) {
        const id = e.row.id
        this.$confirm('请确认是否作废?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          syscodeService.cancelAll({ id: id }).then(data => {
            this.$message({
              type: 'success',
              message: '作废成功!'
            })
            this.refresh()
            this.refreshNodeBy(e.row.parentId)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消作废'
          })
        })
      }
    }
  }
</script>
<style scoped lang="scss">

.app-main-content {
  height: 95%;
  overflow: hidden;
}
/deep/ .org-manage-page .table-wrap {
  min-height: 156px;
}
/deep/ .role-manage .table-wrap {
  min-height: 156px;
}
.button-box{
  margin-bottom: 18px;
}
/deep/ .layout-content{
    overflow: auto;
}
/deep/.el-table__body-wrapper{
  overflow-y: auto;
}
.orgtreee{
  width: 100%;
  overflow: auto;
  height: 100%;
}
</style>
